package com.imicode.hotel.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.imicode.hotel.dao.FoodTypeDao;
import com.imicode.hotel.utils.C3p0Utils;
import com.imicode.hotel.vo.FoodType;

public class FoodTypeC3p0Impl implements FoodTypeDao {
	
	final static String ADDSQL = "insert into foodtype(typeName) values(?)";
	final static String LISTSQL = "select id,typeName from foodtype";
	final static String SEARCHSQL = "select id,typeName from foodtype where typeName like %?%";
	final static String GETSQL = "select id,typeName from foodtype where id=?";
	final static String EDITSQL = "update foodtype set typeName=? where id=?";
	final static String DELETESQL = "delete from foodtype where id=?";

	@Override
	public void save(String name) {
		try {
			QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
			qr.update(ADDSQL, name);			
		} catch (SQLException e) {
			e.printStackTrace();
		} 
	}

	@Override
	public List<FoodType> list(String name) {
		System.out.println("dao impl c3p0 list方法");
		QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
		List<FoodType> list = null;
		try {
			list = qr.query(LISTSQL, new BeanListHandler<FoodType>(FoodType.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public FoodType get(int id) {
		FoodType foodType = null;
		try {
			QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
			foodType = qr.query(GETSQL, new BeanHandler<>(FoodType.class), id);			
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		return foodType;
	}

	@Override
	public void edit(int id, String name) {
		try {
			QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
			qr.update(EDITSQL, name, id);			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void delete(int id) {
		try {
			QueryRunner qr = new QueryRunner(C3p0Utils.getDataSource());
			qr.update(DELETESQL, id);			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
